package com.netintech.process.group.controller;


import com.netintech.common.core.text.Convert;
import com.netintech.common.utils.MessageUtils;
import com.netintech.common.utils.poi.ExcelUtil;
import com.netintech.core.aspectj.lang.annotation.Log;
import com.netintech.core.aspectj.lang.enums.BusinessType;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import com.netintech.core.web.page.TableDataInfo;
import com.netintech.process.group.domain.ActIdGroup;
import com.netintech.process.group.service.IActIdGroupService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程用户组控制器类
 */
@RestController
@RequestMapping("/process/group")
public class ActIdGroupController extends BaseController
{

    @Autowired
    private IActIdGroupService actIdGroupService;


    @Autowired
    private IdentityService identityService;

    /**
     * 查询流程用户组列表
     */
    @PreAuthorize("@ss.hasPermi('process:group:list')")
    @GetMapping("/list")
    public TableDataInfo list(ActIdGroup actIdGroup)
    {
        setPageParam();
        List<ActIdGroup> list = actIdGroupService.selectActIdGroupList(actIdGroup);
        return getDataTable(list);
    }

    /**
     * 导出流程用户组列表
     */
    @PreAuthorize("@ss.hasPermi('process:group:export')")
    @PostMapping("/export")
    public RequestResult export(ActIdGroup actIdGroup)
    {
        List<ActIdGroup> list = actIdGroupService.selectActIdGroupList(actIdGroup);
        ExcelUtil<ActIdGroup> util = new ExcelUtil<ActIdGroup>(ActIdGroup.class);
        return util.exportExcel(list, "用户组");
    }

    /**
     * 新增流程用户组,获取用户信息
     */
    @GetMapping("/users")
    public RequestResult add() {
        return RequestResult.success(identityService.createUserQuery().list());
    }

    /**
     * 新增保存流程用户组
     */
    @PreAuthorize("@ss.hasPermi('process:group:add')")
    @Log(title = "流程用户组", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public RequestResult addSave(@RequestBody ActIdGroup actIdGroup) {
        List<Group> list = identityService.createGroupQuery().groupId(actIdGroup.getId()).list();
        if (CollectionUtils.isNotEmpty(list)) {
            return RequestResult.error(MessageUtils.message("group.id.exist"));
        }
        int result = actIdGroupService.insertActIdGroup(actIdGroup);
        String[] userIds = actIdGroup.getUserIds();
        if(null!=userIds){
            for (String userId: userIds) {
                identityService.createMembership(userId, actIdGroup.getId());
            }
        }
        return returnResult(result);
    }

    /**
     * 修改流程用户组,获取用户和用户组信息
     */
    @GetMapping("/edit/{id}")
    public RequestResult edit(@PathVariable("id") String id) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("actIdGroup", actIdGroupService.selectActIdGroupById(id));
        map.put("users", identityService.createUserQuery().memberOfGroup(id).list());
        return RequestResult.success(map);
    }

    /**
     * 修改保存流程用户组
     */
    @PreAuthorize("@ss.hasPermi('process:group:edit')")
    @Log(title = "流程用户组", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public RequestResult edit(@RequestBody ActIdGroup actIdGroup) {
        int result = actIdGroupService.updateActIdGroup(actIdGroup);
        String[] userIds = actIdGroup.getUserIds();

        List<User> userList = identityService.createUserQuery().memberOfGroup(actIdGroup.getId()).list();
        // 先删后增
        userList.forEach(existUser -> {
            identityService.deleteMembership(existUser.getId(), actIdGroup.getId());
        });
        if(userIds!=null){
            for (String userId: userIds) {
                identityService.createMembership(userId, actIdGroup.getId());
            }
        }
        return returnResult(result);
    }

    /**
     * 删除流程用户组
     */
    @PreAuthorize("@ss.hasPermi('process:group:remove')")
    @Log(title = "流程用户组", businessType = BusinessType.DELETE)
    @DeleteMapping( "/{ids}")
    public RequestResult remove(@PathVariable("ids") String ids) {
        String[] idArr = Convert.toStrArray(ids);
        for(String id : idArr){
            if(CollectionUtils.isNotEmpty(identityService.createUserQuery().memberOfGroup(id).list())){
                return RequestResult.error(MessageUtils.message("user.group.ship.not.remove", id));
            }
        }
        return returnResult(actIdGroupService.deleteActIdGroupByIds(ids));
    }

}
